#include "App_Message.h"

/*
字符数组:  1 2 4 XXabcd
json字符串: {"conn_type": 1, "id": "5858", "msg": "61626364"}
*/
char *App_Message_ArrayToCJSON(char *array, int arrLen)
{
    // 1.从array 中提取conn_type,id_len,msg_len,id, msg
    int conn_type = (int)array[0];
    int id_len = (int)array[1];
    int msg_len = (int)array[2];
    // 2.检查id_len和msg_len是否超出数组长度
    if (id_len + msg_len + 3 > arrLen)
    {
        log_debug("字符串长度错误");
        return NULL;
    }
    // 3.从array 中提取id和msg
    char id[id_len];
    char msg[msg_len];
    memcpy(id, array + 3, id_len);
    memcpy(msg, array + 3 + id_len, msg_len);

    // 4.生成id和msg的16进制字符串
    char *id_hex = App_Common_ArrayToHexString(id, id_len);
    char *msg_hex = App_Common_ArrayToHexString(msg, msg_len);

    // 5.生成json字符串
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "conn_type", conn_type);
    cJSON_AddStringToObject(root, "id", id_hex);
    cJSON_AddStringToObject(root, "msg", msg_hex);
    char *json = cJSON_PrintUnformatted(root);

    // 6.释放内存
    cJSON_Delete(root);
    free(id_hex);
    free(msg_hex);

    // 7.返回json字符串
    return json;
}
/*
字符数组:  1 2 4 XXabcd
json字符串: {"conn_type": 1, "id": "5858", "msg": "61626364"}
*/
int App_Message_CJSONToArray(char *json, char *charbuf, int buf_size)
{
    // 1.解析json字符串
    cJSON *root = cJSON_Parse(json);
    if (root == NULL)
    {
        log_debug("json解析失败");
        return -1;
    }
    // 2.从json中得到conn_type,id_hex,msg_hex
    cJSON *conn_type_obj = cJSON_GetObjectItem(root, "conn_type");
    cJSON *id_obj = cJSON_GetObjectItem(root, "id");
    cJSON *msg_obj = cJSON_GetObjectItem(root, "msg");
    int conn_type = conn_type_obj->valueint;
    char *id_hex = id_obj->valuestring;
    char *msg_hex = msg_obj->valuestring;

    // 3.将id_hex和msg_hex转换为id和msg，并得到id_len和msg_len
    int id_len = 0;
    int msg_len = 0;
    char *id = App_Common_HexStringToArray(id_hex, &id_len);
    char *msg = App_Common_HexStringToArray(msg_hex, &msg_len);

    // 4.计算字符串的长度
    int arr_Len = id_len + msg_len + 3;
    if (arr_Len > buf_size)
    {
        log_debug("字符数组的容量不够");
        return -1;
    }

    // 5.将conn_type,id_len,msg_len,id,msg 写入字符数组中
    charbuf[0] = conn_type;
    charbuf[1] = id_len;
    charbuf[2] = msg_len;
    memcpy(charbuf + 3, id, id_len);
    memcpy(charbuf + 3 + id_len, msg, msg_len);

    // 6.释放内存
    free(id);
    free(msg);
    cJSON_Delete(root);

    return arr_Len;
}
